package graduationorder.graduationorder.handler;

import graduationorder.graduationorder.error.BusinessException;
import graduationorder.graduationorder.error.EmBusinessException;
import graduationorder.graduationorder.result.CommonReturnType;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;

/**
 * @author Mzk
 * @version 1.0
 * @description: 处理Controller层未吸收的异常信息，返回给前端统一错误格式
 * @date 2024/7/14 下午 5:42
 */
@Configuration
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonReturnType exceptionHandler(Exception e){
        HashMap<String, Object> errorMap = new HashMap<>();
        if (e instanceof BusinessException){
            BusinessException exception = (BusinessException) e;
            errorMap.put("errorCode", exception.getErrorCode());
            errorMap.put("errorMsg", exception.getErrorMsg());
        }else {
            errorMap.put("errorCode", EmBusinessException.SERVER_ERROR.getErrorCode());
            errorMap.put("errorMsg", EmBusinessException.SERVER_ERROR.getErrorMsg());
        }
        return CommonReturnType.create(errorMap,"error");
    }
}
